package com.example.mentalhealth.Controller.UserController;

import com.example.mentalhealth.Service.ExamPaperService;
import com.example.mentalhealth.Service.ExamRecordQuestionService;
import com.example.mentalhealth.Service.ExamRecordService;
import com.example.mentalhealth.Service.QuestionService;
import com.example.mentalhealth.entities.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ExamCenterController {

    @Autowired
    public ExamPaperService examPaperService;

    @Autowired
    public ExamRecordService examRecordService;

    @Autowired
    public ExamRecordQuestionService examRecordQuestionService;

    @Autowired
    public QuestionService questionService;

    // 获取所有试卷
    @RequestMapping("/getExamPapers")
    public ResultData getExamPapers(){
        return new ResultData(200, "success", examPaperService.queryAllExamPaper());
    }

    // 保存答卷
    @PostMapping("/submit")
    public ResultData submit(@RequestBody Map<String, Object> submitData){
        Long paperId = Long.parseLong(String.valueOf(submitData.get("paperId")));//试卷id
        Long userId = Long.parseLong(String.valueOf(submitData.get("userId")));//用户id
        Map<String, Object> answers = (Map<String, Object>) submitData.get("answers");//答案
        Date startTime = convertToDate(String.valueOf(submitData.get("startTime")));//开始时间
        Date submitTime =convertToDate(String.valueOf(submitData.get("endTime")));//结束时间
        assert submitTime != null;
        double useTime = (submitTime.getTime() - startTime.getTime())/(1000.0*60.0);//答题时间
        BigDecimal score = BigDecimal.valueOf(0);//存储总分

        //处理答卷
        ExamRecord examRecord = new ExamRecord();//封装答卷
        examRecord.setPaperId(paperId);//设置试卷id
        examRecord.setUserId(userId);//设置用户id
        examRecord.setStartTime(startTime);//设置开始时间
        examRecord.setSubmitTime(submitTime);//设置结束时间
        examRecord.setDuration((int) Math.round(useTime));//设置答题时间
        //得分逻辑
        examRecord.setScore(BigDecimal.valueOf(0));//先默认0分

        //保存答卷
        int result =examRecordService.saveExamRecord(examRecord);

        //保存答卷联系联表
        //获取记录id
        Long record_id = examRecord.getId();
        for (Map.Entry<String, Object> entry : answers.entrySet()) {
            //获取对象
            ExamRecordQuestion examRecordQuestion = new ExamRecordQuestion(); // 假设这是正确的初始化方式
            examRecordQuestion.setRecordId(record_id);//记录id
            examRecordQuestion.setQuestionId(Long.parseLong(entry.getKey()));//问题id
            examRecordQuestion.setUserAnswer(String.valueOf(entry.getValue()));//用户答案

            //判断答案是否正确
            Question question = questionService.queryQuestionsByID(Integer.parseInt(entry.getKey()));
            String correctAnswer = question.getAnswer();//获取正确答案

            //1.判断题目类型
            int type = question.getType();//题目类型
            if (type == 1 || type == 2) {
                //处理单选题和多选题
                String userAnswer = entry.getValue().toString();
                String userAnswerOption = userAnswer.substring(0, 1);
                //提取答案选项
                if(type==2){
                    String[] parts = userAnswer.substring(1, userAnswer.length() - 1).split(", ");
                    // 使用 StringBuilder 拼接字符串
                    StringBuilder userOption = new StringBuilder();
                    for (String part : parts) {
                        userOption.append(part);
                    }
                    userAnswerOption = userOption.toString();
                }
                //判断答案是否正确
                if(userAnswerOption.equals(correctAnswer)){
                    examRecordQuestion.setIsCorrect(true);
                    examRecordQuestion.setScore(question.getScore());
                    if(question.getScore() != null){
                        score = score.add(question.getScore());
                    }
                }else {
                    examRecordQuestion.setIsCorrect(false);//设置为错误
                    examRecordQuestion.setScore(BigDecimal.ZERO);//设置为0分
                }
            }else {
                examRecordQuestion.setIsCorrect(false);//设置为错误
                examRecordQuestion.setIsCheck(0);//设置为未批改
            }

            int i =examRecordQuestionService.saveExamRecordQuestion(examRecordQuestion);
            if (i > 0) {
                System.out.println("保存答卷联表成功");
            }else {
                System.out.println("保存答卷联表失败");
            }

        }
        examRecordService.updateScoreById(record_id,score);//更新总分
        System.out.println("总分：" + score);
        return new ResultData(200, "success");
    }

    // 时间转换
    public static Date convertToDate(String isoString) {
        try {
            // ISO 8601格式解析器
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
            return sdf.parse(isoString);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


}
